import requests
import os
from datetime import datetime

# 获取当前用户的桌面路径
desktop_path = os.path.join(os.environ['USERPROFILE'], 'Desktop')

# === 获取今天的日期 ===
default_date = datetime.now().strftime("%Y-%m-%d")

# === 用户输入日期 ===
input_date = input(f"请输入导出日期（格式: YYYY-MM-DD），默认使用今天日期 ({default_date}): ").strip()

# 如果用户没有输入日期，使用默认日期
if not input_date:
    input_date = default_date

# 登录信息
login_url = "http://24.46.6.14:8082/fqfhyc/binfo_sys/user/login"
login_payload = {
    "first": "admin",
    "pwd": "Tzdd@2024!"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Mobile Safari/537.36",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Origin": "http://24.46.6.14:8082",
    "Referer": "http://24.46.6.14:8082/fqfhyc/login.html",
    "X-Requested-With": "XMLHttpRequest",
    "Pragma": "no-cache"
}

# 拼接导出接口 URL
export_url = f"http://24.46.6.14:8082/fqfhyc/measured/export_by_current_user?date={input_date}"

# 文件保存路径
excel_filename = f"历史负荷曲线_{input_date.replace('-', '')}.xlsx"
excel_save_path = os.path.join(desktop_path, excel_filename)

# 创建 Session 会话
session = requests.Session()

try:
    # 登录
    login_response = session.post(login_url, json=login_payload, headers=headers, timeout=10)
    login_response.raise_for_status()
    print("✅ 登录成功")

    # 下载 Excel，设置超时为 60 秒
    download_response = session.get(export_url, headers=headers, timeout=60)
    download_response.raise_for_status()

    # 写入 Excel 文件
    with open(excel_save_path, "wb") as f:
        f.write(download_response.content)

    print(f"✅ Excel 文件已保存到：{excel_save_path}")

except requests.exceptions.Timeout:
    print("❌ 请求超时！导出 Excel 的时间超过了 60 秒，请稍后重试。")

except requests.RequestException as e:
    print("❌ 请求异常：", e)

input("按 Enter 键退出...")
